package com.fram.service.api.v1.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fram.bean.api.circle.request.CircleAddRequest;
import com.fram.bean.api.circle.request.CircleOperateRequest;
import com.fram.bean.api.circle.request.CircleSeachRequest;
import com.fram.bean.api.circle.response.CircleSeachResponse;
import com.fram.bean.api.news.request.CommentSearchRequest;
import com.fram.bean.api.news.response.CommentSearchResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.area.AreaUtils;
import com.fram.common.util.area.bean.baidu.AddressCode;
import com.fram.common.util.base.BaseService;
import com.fram.common.util.qiniu.QiniuUtils;
import com.fram.common.util.tencent.TencentUtils;
import com.fram.entity.NewsComment;
import com.fram.entity.NewsList;
import com.fram.entity.OrderMain;
import com.fram.entity.ResOperate;
import com.fram.entity.ResourceCircle;
import com.fram.mapper.NewsCommentMapper;
import com.fram.mapper.NewsListMapper;
import com.fram.mapper.OrderMainMapper;
import com.fram.mapper.ResOperateMapper;
import com.fram.mapper.ResourceCircleMapper;
import com.fram.service.api.v1.ResourceCircleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class ResourceCircleServiceimpl extends BaseService implements ResourceCircleService {

	@Autowired
	private ResourceCircleMapper resourceCircleMapper;

	@Autowired
	private ResOperateMapper operateMapper;
	@Autowired
	private NewsListMapper newsListMapper;
	@Autowired
	private QiniuUtils qiniuUtils;
	@Autowired
	private NewsCommentMapper newsCommentMapper;
	@Autowired
	private OrderMainMapper orderMainMapper;
	@Autowired
	private TencentUtils tencentUtils;

	/****/
	@Override
	public PageInfo<CircleSeachResponse> list(PageBean<CircleSeachRequest> request) throws ProException {
		// 根据经纬度获取地址
		// if (!StringUtils.isEmpty(request.getParam().getLongitude()) && !StringUtils.isEmpty(request.getParam().getLatitude())) {
		// String cityCode = AreaUtils.getCityCode(request.getParam().getLongitude(), request.getParam().getLatitude()).getCityCode();
		// if (!StringUtils.isEmpty(cityCode)) {
		// request.getParam().setCityCode(cityCode);
		// }
		// }
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<CircleSeachResponse> list = resourceCircleMapper.selectByCode(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		for (CircleSeachResponse r : list) {
			switch (r.getResType()) {
			case PublicConstant.RES_TYPE_6:
				r.setResData(orderMainMapper.circleQueryBasic(r.getResId()));
				break;
			}
		}
		return new PageInfo<>(list);
	}

	/** 添加发布 种植经验圈 **/
	@Override
	public void add(CircleAddRequest request) throws ProException {
		String key = PublicMethod.getMd5(request.getUserId() + request.getContent() + request.getImg(), 1, true);
		int db = 12;
		if (redisService.get(db, key) != null) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "请勿重复提交相同数据");
		}
		redisService.set(db, key, "1", 10);
		// 字数限制
		if (PublicConstant.RES_TYPE_7 == request.getResType().intValue() && StringUtils.isEmpty(request.getImg())
				&& (request.getContent().length() < 5 || request.getContent().length() > 256)) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "发布字数在5-256之间");
		}
		// 根据经纬度获取地址
		if (StringUtils.isEmpty(request.getLongitude()) || StringUtils.isEmpty(request.getLatitude())) {
			throw new ProValiDataException(ErrCode.ERR_PARAMETER.getReturnCode(), "经纬度必传");
		}
		// 判断资源类型是否存在
		switch (request.getResType()) {
		case PublicConstant.RES_TYPE_6:
			OrderMain order = orderMainMapper.selectByPrimaryKey(request.getResId());
			if (order == null) {
				throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), "您分享的订单不存在");
			}
			if (order.getUserId().longValue() != request.getUserId().longValue()) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "您无权分享该订单");
			}
			break;
		}
		if (!StringUtils.isEmpty(request.getContent())) {
			tencentUtils.checkMsg(request.getContent());
		}
		AddressCode address = AreaUtils.getCityCode(request.getLongitude(), request.getLatitude());
		if (!StringUtils.isEmpty(request.getImg())) {
			request.setImg(qiniuUtils.uploadImageUrl(request.getImg()));
		}
		if (StringUtils.isEmpty(address.getCityCode())) {
			throw new ProValiDataException(ErrCode.ERR_PARAMETER.getReturnCode(), "经纬度获取地址失败");
		}
		request.setProvinceCode(address.getProvinceCode());
		request.setCityCode(address.getCityCode());
		request.setAreaCode(address.getAreaCode());
		if (resourceCircleMapper.insertSelective(request) == 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

	/** 删除 等于 修改 EmptyDelete 为1 **/
	@Override
	public void update(ResourceCircle record) throws ProException {
		if (resourceCircleMapper.updateByPrimaryKeySelective(record) == 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

	@Override
	public String operateCircle(CircleOperateRequest request) throws ProAffairException {
		if (request.getId() == null) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		if (PublicConstant.OPERATE_TYPE_1 == request.getOperateType()) {// 点赞
			ResOperate operate = new ResOperate();
			operate.setUserId(request.getUserId());
			operate.setResId(request.getId());
			operate.setResType(request.getResType());
			operate.setType(PublicConstant.OPERATE_TYPE_1);
			ResOperate query = operateMapper.select(operate);
			if (query == null) {// 没有操作过
				if (operateMapper.insertSelective(operate) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "点赞失败");
				}
				resAdditionAndSubtractionNumber(operate, 1);
				return "点赞成功";
			} else {
				if (operateMapper.deleteByPrimaryKey(query.getId()) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "取消点赞失败");
				}
				resAdditionAndSubtractionNumber(operate, -1);
				return "取消点赞成功";
			}
		}
		throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "操作失败");
	}

	/** 资源操作加减数量 number为负数则减 **/
	public void resAdditionAndSubtractionNumber(ResOperate operate, int number) throws ProAffairException {
		if (PublicConstant.OPERATE_TYPE_2 == operate.getType() && (PublicConstant.RES_TYPE_9 == operate.getResType())) {// 在看+1
			NewsList news = newsListMapper.selectByPrimaryKey(operate.getResId());
			if (news == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "操作数据不存在");
			}
			news.setLookNumber(news.getLookNumber() + number);
			if (newsListMapper.updateByPrimaryKeySelective(news) == 0) {
				throw new ProRunTimeException(ErrCode.NEWS_OPERATE_FAIL.getReturnCode(), ErrCode.NEWS_OPERATE_FAIL.getReturnMsg());
			}
		}
		if (PublicConstant.OPERATE_TYPE_1 == operate.getType() && PublicConstant.RES_TYPE_9 == operate.getResType()) {// 点赞+1
			NewsComment comment = newsCommentMapper.selectByPrimaryKey(operate.getResId());
			if (comment == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "操作数据不存在");
			}
			comment.setZanNumber(comment.getZanNumber() + number);
			if (newsCommentMapper.updateByPrimaryKeySelective(comment) == 0) {
				throw new ProRunTimeException(ErrCode.NEWS_OPERATE_FAIL.getReturnCode(), ErrCode.NEWS_OPERATE_FAIL.getReturnMsg());
			}
		}
	}

	/** 评论列表 **/
	@Override
	public PageInfo<CommentSearchResponse> selectCommentForApiList(PageBean<CommentSearchRequest> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		request.getParam().setOperateZanResType(PublicConstant.RES_TYPE_9);
		List<CommentSearchResponse> list = newsCommentMapper.selectCommentForApiList(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	/** 增加评论 **/
	@Override
	public NewsComment addComment(NewsComment request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getContent())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		if (request.getContent().length() < 2 || request.getContent().length() > 200) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "评论字数在2-200之间");
		}
		if (!StringUtils.isEmpty(request.getContent())) {
			try {
				tencentUtils.checkMsg(request.getContent());
			} catch (ProException e) {
				throw new ProRunTimeException(e.getErrorMsg());
			}
		}
		if (newsCommentMapper.insertSelective(request) == 0) {
			throw new ProRunTimeException(ErrCode.NEWS_COMMENT_FAIL.getReturnCode(), ErrCode.NEWS_COMMENT_FAIL.getReturnMsg());
		}
		if (request.getId() == null) {
			throw new ProRunTimeException(ErrCode.NEWS_COMMENT_FAIL.getReturnCode(), ErrCode.NEWS_COMMENT_FAIL.getReturnMsg());
		}
		CommentSearchRequest queryRequest = new CommentSearchRequest();
		queryRequest.setId(request.getId());
		queryRequest.setResId(request.getResId());
		queryRequest.setResType(request.getResType());
		queryRequest.setTopId(request.getTopId());
		queryRequest.setUserId(request.getUserId());
		queryRequest.setOperateZanResType(PublicConstant.RES_TYPE_9);
		List<CommentSearchResponse> list = newsCommentMapper.selectCommentForApiList(queryRequest);
		if (list == null || list.size() == 0 || list.size() != 1) {
			throw new ProRunTimeException(ErrCode.NEWS_COMMENT_FAIL.getReturnCode(), ErrCode.NEWS_COMMENT_FAIL.getReturnMsg());
		}
		return list.get(0);
	}
}
